package com.springcloud.demo.dynamicTable.autocode.controller;

import com.springcloud.demo.dynamicTable.autocode.service.GeneratorService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RequestMapping("/generator")
@Controller
public class GeneratorController {
	@Autowired
	GeneratorService generatorService;

	@GetMapping("/code")
	public void code(HttpServletResponse response, @RequestParam(value = "tableName") String tableName)
            throws IOException {
		String[] tableNames = new String[] { tableName };
		byte[] data = generatorService.generatorCode(tableNames);
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=\"pandora.zip\"");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");

		IOUtils.write(data, response.getOutputStream());
	}

	@GetMapping("/batchCode")
	public void batchCode(HttpServletResponse response, @RequestParam(value = "tables") String tables) throws IOException {
		String[] tableNames = tables.split(",");
		byte[] data = generatorService.generatorCode(tableNames);
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=\"pandora.zip\"");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");

		IOUtils.write(data, response.getOutputStream());
	}
}
